package org.easy.http.client.cookie;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author WuXueLi
 * @Date 15:41 2023/2/4
 * @Version 1.0
 **/
public class EasyMemoryCookieStore implements EasyCookieStore{

    private final Map<String,List<Cookie>> allCookies = new ConcurrentHashMap<>();


    @Override
    public void add(HttpUrl uri, List<Cookie> cookies) {
        if (Objects.isNull(uri)) {
            throw new NullPointerException("Uri must not be null.");
        }

        if (cookies.isEmpty()) {
            throw new NullPointerException("Cookies must not be null.");
        }

        List<Cookie> oldCookies = allCookies.get(uri.host());
        oldCookies.addAll(cookies);
        List<Cookie> newCookies = oldCookies.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Cookie::name))),
        ArrayList::new));
        allCookies.put(uri.host(),newCookies);
    }

    @Override
    public List<Cookie> get(HttpUrl uri) {
        if (Objects.isNull(uri)) {
            throw new NullPointerException("Uri must not be null.");
        }
        return allCookies.get(uri.host());
    }

    @Override
    public List<Cookie> getCookies() {
        List<Cookie> cookies = new ArrayList<>();
        allCookies.values().forEach(cookies::addAll);
        return cookies;
    }

    @Override
    public boolean remove(HttpUrl uri, Cookie cookie) {
        if (uri == null) {
            throw new NullPointerException("Uri must not be null.");
        }
        if (cookie == null) {
            throw new NullPointerException("Cookie must not be null.");
        }
        return allCookies.remove(uri.host()) != null;
    }

    @Override
    public boolean removeAll() {
        allCookies.clear();
        return Boolean.TRUE;
    }
}
